package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.gts.bpaas.middleware.mq.api.MessageProducer;
import com.aliyun.gts.bpaas.middleware.mq.api.exception.MQException;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.MqMessageContext;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lilh
 * @date 2021/4/23 13:42
 */
@Slf4j
public class MqProducer {

    private MessageProducer messageProducer;

    private String topic;

    public MqProducer(MessageProducer messageProducer, String topic) {
        this.messageProducer = messageProducer;
        this.topic = topic;
    }

    public void sendMessage(MqMessageContext messageContext) {
        log.info("发送的mq消息为：{}", JSONObject.toJSONString(messageContext));
        try {
            String result = messageProducer.send(topic, messageContext.getTag(),
                    messageContext.getPayload(),
                    messageContext.getProperties());
            log.info("发送mq消息返回结果为：{}", result);
        } catch (MQException e) {
            //将消息保存到本地，定时再发送
            log.error("发送mq消息失败，异常信息为：", e);
        }
    }
}
